package com.cjc.hotel.server.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * app登录拦截器
 *
 * @author Administrator
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ApplicationContext applicationContext;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        boolean flag = false;
        String[] release = new String[]{"/admin/login","/admin/register","/admin/toLogin","/admin/toRegister"};
        if(servletPath.startsWith("/error")){
            return true;
        }
        if(servletPath.startsWith("/admin")){
            for (String s : release) {
                flag = servletPath.startsWith(s);
                if(flag){
                    break;
                }
            }
            if(!flag){
                HttpSession session = request.getSession();
                Object user = session.getAttribute("admin");
                if(user == null){
                    response.sendRedirect(contextPath+"/admin/toLogin");
                    return false;
                }

            }
        }else if(!servletPath.startsWith("/static")) {
            response.sendRedirect(contextPath+"/admin/toLogin");
            return false;
        }

        return true;
    }
}
